package com.chat.demo.userservice.Entity.DAO;

import com.chat.demo.userservice.Entity.Entity.ChatRoom;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ChatRoomMapper {

    // 创建聊天室
    @Insert("INSERT INTO app.chat_room(room_name, creator_id, type, description) " +
            "VALUES (#{roomName}, #{creatorId}, #{type}, #{description})")
    @Options(useGeneratedKeys = true, keyProperty = "roomId", keyColumn = "room_id")
    int createRoom(ChatRoom room);

    // 删除聊天室（限制仅创建者或管理员操作由业务层判断）
    @Delete("DELETE FROM app.chat_room WHERE room_id = #{roomId}")
    int deleteRoom(@Param("roomId") int roomId);

    // 邀请用户加入聊天室
    @Insert("INSERT INTO app.user_chat_room(user_id, room_id, role) " +
            "VALUES(#{userId}, #{roomId}, #{role})")
    int inviteUser(@Param("userId") int userId, @Param("roomId") int roomId, @Param("role") String role);

    // 设置成员角色
    @Update("UPDATE app.user_chat_room SET role = #{role} " +
            "WHERE user_id = #{userId} AND room_id = #{roomId}")
    int updateUserRole(@Param("userId") int userId, @Param("roomId") int roomId, @Param("role") String role);

    // 移除成员
    @Delete("DELETE FROM app.user_chat_room WHERE user_id = #{userId} AND room_id = #{roomId}")
    int removeUser(@Param("userId") int userId, @Param("roomId") int roomId);

    // 主动加入聊天室
    @Insert("INSERT INTO app.user_chat_room(user_id, room_id, role) " +
            "VALUES(#{userId}, #{roomId}, 'member')")
    int joinRoom(@Param("userId") int userId, @Param("roomId") int roomId);

    // 主动退出聊天室
    @Delete("DELETE FROM app.user_chat_room WHERE user_id = #{userId} AND room_id = #{roomId}")
    int leaveRoom(@Param("userId") int userId, @Param("roomId") int roomId);

    // 判断是否是创建者
    @Select("SELECT COUNT(*) FROM app.chat_room WHERE room_id = #{roomId} AND creator_id = #{userId}")
    boolean isCreator(@Param("roomId") int roomId, @Param("userId") int userId);

    // 判断是否是管理员
    @Select("SELECT COUNT(*) FROM app.user_chat_room WHERE room_id = #{roomId} AND user_id = #{userId} AND role = 'admin'")
    boolean isAdmin(@Param("roomId") int roomId, @Param("userId") int userId);

    // 判断是否是普通成员
    @Select("SELECT COUNT(*) FROM app.user_chat_room WHERE room_id = #{roomId} AND user_id = #{userId} AND role = 'member'")
    boolean isMember(@Param("roomId") int roomId, @Param("userId") int userId);

    // 根据用户ID获取其所属的聊天室ID列表
    @Select("SELECT room_id FROM app.user_chat_room WHERE user_id = #{userId}")
    List<Long> getRoomIdsByUserId(int userId);
}
